<?php
/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2019/9/12
 * Time: 11:33
 */

namespace p5\html;


class HtmlParser
{

    static public function toStyleString($attributes)
    {
        $list = [];
        foreach ($attributes as $key => $value) {
            array_push($list, "{$key}:$value");
        }
        return implode(";", $list);
    }

    static public function parseStyle($style)
    {
        $attributes = [];
        $matrix = explode(";", $style);
        foreach ($matrix as $item) {
            $temp = explode(":", $item);
            if (count($temp) === 1) {
                $attributes[trim($temp[0])] = "";
            } else if (count($temp) === 2) {
                $attributes[trim($temp[0])] = trim($temp[1]);
            }
        }
        return $attributes;
    }

    /**
     * 将 html 按照标签（如 img,div 拆分成多个段
     * @param $html string
     * @param $tagName string
     * @return array
     */
    static public function splitByTag($html, $tagName)
    {
        $segments = [];
        $temp = $html;
        while (!empty($temp)) {
            $index = strpos($temp, "<" . $tagName);
            if ($index === false) {
                // 后面没有这个标签了
                array_push($segments, $temp);
                break;
            }
            // echo $index . "<br/>";
            $prefix = substr($temp, 0, $index);
            array_push($segments, $prefix);
            $temp = substr($temp, $index);
            $end1 = strpos($temp, "/>");
            $end2 = strpos($temp, "</" . $tagName . ">");
            $end = static::getValidEnd($end1, $end2);
            if ($end === 0) {
                // 标签找不到结束
                array_push($segments, $temp);
                break;

            } else {
                $end = strpos($temp, ">", $end) + 1;
                $tagHtml = substr($temp, 0, $end);
                array_push($segments, $tagHtml);
                $temp = substr($temp, $end);
            }
        }
        return $segments;
    }

    static public function isTag($html, $tagName)
    {
        return strpos($html, "<" . $tagName) === 0;
    }

    private static function getValidEnd($end1, $end2)
    {
        if ($end1 === false && $end2 === false) {
            return 0;
        }
        if ($end1 === false) {
            return $end2;
        }
        if ($end2 === false) {
            return $end1;
        }
        return min($end1, $end2);
    }
}